import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import classNames from 'classnames';
import { Icon } from '@library';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import styles from './collapse.module.scss';

const isEn = localStorage.i18nextLng === 'en';
const T = window.$app.t;

export interface CollapseProps extends CanvasItemProps {
  name: string;
  onValuesChange(id: string, value: string): void;
  _id?: string;
  collapseProps?: {
    title?: string;
    titleEn?: string;
    defaultOpen?: boolean
  }
}

export default forwardRef((props: CollapseProps, ref: React.Ref<{ setOpen: Function }>) => {
  const { collapseProps, domComplete, children, isDesign, ...canvasProps } = props;
  const [open, setOpen] = useState(false);

  useQueryControlWrap(canvasProps.id, '', domComplete);

  useEffect(() => {
    if(collapseProps?.defaultOpen) setOpen(true);
  }, [collapseProps?.defaultOpen]);

  useImperativeHandle(ref, () => ({
    setOpen
  }));

  return (
    <div {...canvasProps} className={classNames(styles.box, {
      [styles.hide]: !isDesign && !open
    })}>
      <div className={styles.header}>
        {(isEn ? collapseProps?.titleEn : collapseProps?.title) || <span/>}
        <Icon onClick={() => setOpen(!open)} icon={open ? '\ue652' : '\ue64c'}/>
      </div>
      <div className={styles.children}>
        {children?.length > 0 || children?.type ? (
          <>
            {children}
            {isDesign && <div className={styles.addTip}>{T('addComponentTip')}</div>}
          </>
        ) : (
          isDesign && <div className={styles.addTip}>{T('addComponentTip')}</div>
        )}
      </div>
    </div>
  );
});